//
// Created by dg on 2024/1/2.
//

#include "BLYUVTextureFrameCopier.h"
#include "Commontool.h"

#define LOG_TAG "LYUVTextureFrameCopier"

BLYUVTextureFrameCopier::BLYUVTextureFrameCopier() {
    mVertexShader = NO_FILTER_VERTEX_SHADER;
    mFragmentShader = YUV_FRAME_FRAGMENT_SHADER;
}

BLYUVTextureFrameCopier::~BLYUVTextureFrameCopier() {

}

bool BLYUVTextureFrameCopier::init() {
    mGLProgId = loadProgram(mVertexShader, mFragmentShader);
    if (!mGLProgId) {
        LOGE("Could not create program");
        return false;
    }

    mGLVertexCoords = glGetAttribLocation(mGLProgId, "vPosition");
    checkGlError("glGetAttribLocation(mGLProgId, \"vPosition\")");
    mGLTextureCoords = glGetAttribLocation(mGLProgId, "vTexCords");
    checkGlError("glGetAttribLocation(mGLProgId, \"vTexCords\")");
    glUseProgram(mGLProgId);
    _unformSamplers[0] = glGetUniformLocation(mGLProgId, "s_texture_y");
    _unformSamplers[1] = glGetUniformLocation(mGLProgId, "s_texture_u");
    _unformSamplers[2] = glGetUniformLocation(mGLProgId, "s_texture_v");

    mUniformTransforms = glGetUniformLocation(mGLProgId, "trans");
    checkGlError("glGetUniformLocation(mGLProgId, \"trans\")");

    mUniformTexMatrix = glGetUniformLocation(mGLProgId, "texMatrix");
    checkGlError("glGetUniformLocation mUniformTexMatrix");

    mIsInitialized = true;
    return true;
}
void BLYUVTextureFrameCopier::renderWithCoords(BLTextureFrame *textureFrame, GLuint texId, GLfloat *vertexCoords, GLfloat*textureCoords) {
    glBindTexture(GL_TEXTURE_2D, texId);
    checkGlError("glBindTexture");

// glFramebufferTexture2D 将二维纹理绑定到帧缓冲区
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                           texId, 0);
    checkGlError("glFramebufferTexture2D");

    glUseProgram(mGLProgId);
    if (!mIsInitialized) {
        return;
    }
    glVertexAttribPointer(mGLVertexCoords, 2, GL_FLOAT, GL_FALSE, 0, vertexCoords);
    glEnableVertexAttribArray (mGLVertexCoords);
    glVertexAttribPointer(mGLTextureCoords, 2, GL_FLOAT, GL_FALSE, 0, textureCoords);
    glEnableVertexAttribArray (mGLTextureCoords);
    /* Binding the input texture */
    textureFrame->bindTexture(_unformSamplers);

    float texTransMatrix[4 * 4];
    matrixSetIdentityM(texTransMatrix);
    glUniformMatrix4fv(mUniformTexMatrix, 1, GL_FALSE, (GLfloat *) texTransMatrix);

    float rotateMatrix[4 * 4];
    matrixSetIdentityM(rotateMatrix);
    glUniformMatrix4fv(mUniformTransforms, 1, GL_FALSE, (GLfloat *) rotateMatrix);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glDisableVertexAttribArray(mGLVertexCoords);
    glDisableVertexAttribArray(mGLTextureCoords);
    glBindTexture(GL_TEXTURE_2D, 0);
//  glFramebufferTexture2D   将二维纹理从帧缓冲区解绑 主要是参数的变化
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
}

